package me.illtamer.infinite.util;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class SecurityUtil {

    private static final char[] SALTS = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    private SecurityUtil() {}

    /**
     * 随机生成盐
     * @param length 获取的盐的长度
     * */
    @NotNull
    public static String salt(int length) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        int range = SALTS.length;
        while (builder.length() != length)
            builder.append(SALTS[random.nextInt(range)]);
        return builder.toString();
    }

    @NotNull
    public static String md5(String str) {
        if (str == null) return "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            byte[] digest  = md5.digest(str.getBytes(StandardCharsets.UTF_8));
            // 16是表示转换为16进制数
            return new BigInteger(1, digest).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return str;
    }

    @NotNull
    public static String urlEncode(String ori) {
        if (ori == null) return "";
        try {
            return URLEncoder.encode(ori, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ori;
    }

    @NotNull
    public static String urlDecode(String urlEncode) {
        if (urlEncode == null) return "";
        try {
            return URLDecoder.decode(urlEncode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return urlEncode;
    }

}
